﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace HostsOperate
{
    /// <summary>
    /// 操作帮助类
    /// </summary>
    public class HostsHelper
    {
        //当前hosts文件的位置
        private string _FileName = Environment.GetEnvironmentVariable("systemdrive")+@"\Windows\System32\drivers\etc\hosts";
        public List<HostData> HostDatas;
        public HostsHelper()
        {
            HostDatas = new List<HostData>();
            //加载 内容
            LoadData();
        }
        //读取文件中内容
        private void LoadData()
        {
            //1.判断文件是否存在
            if (File.Exists(_FileName) == false)
                throw new Exception("获取系统文件失败,_FileName=" + _FileName);
            FileStream stream = new FileStream(_FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            StreamReader reader = new StreamReader(stream);
            try
            {
         
                bool isStart = false;
                while (!reader.EndOfStream)
                {
                    string line = reader.ReadLine();
                    //如果为空行忽略
                    if (string.IsNullOrEmpty(line))
                        continue;
                    //判断开始位置
                    if (line.Contains("localhost "))
                    {
                        isStart = true;
                        continue;
                    }

                    if (isStart)
                    {
                        string[] tempList = line.Split(new string[] { "\t", " " }, StringSplitOptions.RemoveEmptyEntries);
                        //如果结果长度为 2或3
                        if (tempList.Length == 2)
                        {
                            HostDatas.Add(new HostData(true, tempList[0], tempList[1]));
                        }
                        else if (tempList.Length == 3)
                        {
                            if (tempList[0] == "#")
                            {
                                HostDatas.Add(new HostData(false, tempList[1], tempList[2]));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("初始化读取hosts文件中数据失败！", ex);
            }
            finally
            {
                reader.Close();
                stream.Close();
            }
        }
        /// <summary>
        /// 读取hosts 文件中的介绍部分
        /// </summary>
        /// <returns></returns>
        private void ReadSummary(StringBuilder builder)
        {
            FileStream stream = new FileStream(_FileName, FileMode.Open, FileAccess.Read, FileShare.Read);
            StreamReader reader = new StreamReader(stream);
            try
            {
                bool isRead = true;
                while (isRead)
                {
                    string line = reader.ReadLine();
                    if (line.Contains("localhost "))
                    {
                        isRead = false;
                    }
                    builder.AppendLine(line);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("读取host文件中得介绍失败", ex);
            }
            finally
            {
                reader.Close();
                stream.Close();
            }
        }
        //将结果写入文件
        public void WriteData()
        {
            StringBuilder builder = new StringBuilder(2000);
            //1.读取 介绍部分
            ReadSummary(builder);
            //2.组织数据部分
            foreach (var item in HostDatas)
            {
                builder.Append(item.IsEnable ? " " : "#");
                builder.Append("\t");
                builder.Append(string.Format("{0,-15}", item.IP));
                builder.Append("\t\t");
                builder.Append(item.HostName);
                builder.AppendLine();
            }
            StreamWriter writer = new StreamWriter(_FileName, false);
            try
            {
                writer.Write(builder.ToString());
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                writer.Close();
            }
        }
        /// <summary>
        /// 判断相同 iP和域名的数据是否存在
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public bool Exists(HostData item)
        {
            return HostDatas.Any(q => q.IP == item.IP && q.HostName == item.HostName);
        }
        //添加内容
        public bool Add(HostData item)
        {
            if (Exists(item))
                return false;
            HostDatas.Add(item);
            WriteData();
            return true;
        }
        //删除内容
        public bool Remove(HostData item)
        {
            if (Exists(item) == false)
                return false;
            List<HostData> thisList = HostDatas.Where(q => q.HostName == item.HostName && q.IP == item.IP).ToList();
            if (thisList.Count <= 0)
                return false;
            thisList.ForEach(q => HostDatas.Remove(q));
            WriteData();
            return true;
        }
        //修改是否可用
        public bool Enable(string IP, string HostName)
        {
            HostData thisItem = HostDatas.FirstOrDefault(q => q.IP == IP && q.HostName == HostName);
            if (thisItem == null)
                return false;
            thisItem.IsEnable = !thisItem.IsEnable;
            WriteData();
            return true;
        }
    }
    public class HostData
    {
        public HostData(bool IsEnable, string IP, string HostName)
        {
            this.IsEnable = IsEnable;
            this.IP = IP;
            this.HostName = HostName;
        }

        //是否可用
        public bool IsEnable { get; set; }
        public string IP { get; set; }
        public string HostName { get; set; }
    }
}
